<?php
/**
 * Created by PhpStorm.
 * User: thorjiang
 * Date: 2018/7/14
 * Time: 16:59
 */

namespace App\Http\Controllers\API;

use Response;
use App\Http\Controllers\AppBaseController;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use Log;

/**
 * 系统通用接口
 * Class AppController
 * @package App\Http\Controllers\API
 */
class AppController extends AppBaseController
{
    const QINIU = 'http://iccdn.xiaojili.cn/';

    public function uploadAction()
    {
        $accessKey = config('customer.qiniu_ak');
        $secretKey = config('customer.qiniu_sk');
        $bucket = config('customer.qiniu_bucket');

        $auth = new Auth($accessKey, $secretKey);
        $data =  $auth->uploadToken($bucket);

        $ret = ['status'=> 0,
           // 'data'=>$data,
            'uptoken' => $data,
            'msg'=> empty($msg)? '操作成功':$msg,
        ];

        return response()->json($ret);
    }

    /**
     * Store a newly created FacilityModel in storage.
     * POST /facilityModels
     *
     * @param CreateFacilityModelAPIRequest $request
     *
     * @return Response
     *  success
        {
        "file_path": "domain/5fb239f2-0007-40c1-b8e6-0dc11b22779c.jpg",
        "msg": "上传成功",
        "success": true
        }

        fail
        {
        "success": false,
        "msg": "error message",
        "file_path": "[real file path]"
        }
     */
    public function uploadImage()
    {
        Log::info("上传图片");
        $key = '';
        $image = $this->request->file('upload_file', null);
        $type = $this->request->get('type', 1);
        if (empty($image)) {
            return $this->error(1, '图片不存在');
        }

        if ($type == 1) {
            $accessKey = config('customer.qiniu_ak');
            $secretKey = config('customer.qiniu_sk');
            $bucket = config('customer.qiniu_bucket');

            $auth = new Auth($accessKey, $secretKey);
            $token =  $auth->uploadToken($bucket);
            // 要上传文件的本地路径
            $filePath = $image->getRealPath();
            // 上传到七牛后保存的文件名
            $key = 'meeting/image_' . time() . "_" . $image->getClientOriginalName();
            // 初始化 UploadManager 对象并进行文件的上传
            $uploadMgr = new UploadManager();
            // 调用 UploadManager 的 putFile 方法进行文件的上传
            list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
        }

        if ($err === null) {
            $ret = [
                'success' => 'true',
                "msg" => "上传成功",
                'file_path' => self::QINIU . $key,
            ];

            return response()->json($ret);
        } else {
            $ret = [
                'success' => 'false',
                "msg" => "上传失败",
                "file_path" => [],

            ];

            return response()->json($ret);
        }
    }
}
